const webpack = require("webpack");
const UglifyJsPlugin = require("uglifyjs-webpack-plugin");
// gzip压缩
const CompressionWebpackPlugin = require("compression-webpack-plugin");
const path = require("path");

function resolve(dir) {
  return path.join(__dirname, dir);
}

const postcssPresetEnv = require("postcss-preset-env");

const time_version = new Date().getTime();

// 是否为生产环境
const isProduction = process.env.NODE_ENV === "'production'";
console.log('isProduction', isProduction)
// 本地环境是否需要使用cdn
const devNeedCdn = false;

// cdn链接
const cdn = {
  // cdn：模块名称和模块作用域命名（对应window里面挂载的变量名称）
  externals: {
    // vue: "Vue",
    // vuex: "Vuex",
    // "vue-router": "VueRouter",
    // moment: "moment",
    // vant: "vant",
  },
  // cdn的css链接
  // css: ["//cdn.jsdelivr.net/npm/vant@2.5.9/lib/index.min.css"],
  // cdn的js链接
  js: [
    // "//cdn.staticfile.org/vue/2.6.11/vue.min.js",
    // "//cdn.staticfile.org/vuex/3.1.3/vuex.min.js",
    // "//cdn.staticfile.org/vue-router/3.1.3/vue-router.min.js",
    // "//cdn.staticfile.org/axios/0.19.2/axios.min.js",
    // "//cdn.staticfile.org/moment.js/2.24.0/moment.min.js",
    // "//cdn.jsdelivr.net/npm/vant@2.5.9/lib/vant.min.js",
  ],
};

module.exports = {
  // 基本路径
  publicPath: process.env.VUE_APP_ISAPP == "true" ? "./" : "/",
  // 输出文件目录
  outputDir: "dist",
  lintOnSave: false,
  runtimeCompiler: false,
  chainWebpack: (config) => {
    // 移除 prefetch 插件
    config.plugins.delete("prefetch");
    // 移除 preload 插件
    config.plugins.delete("preload");

    config.plugin("html").tap((args) => {
      // 生产环境或本地需要cdn时，才注入cdn
      if (isProduction || devNeedCdn) args[0].cdn = cdn;
      return args;
    });

    config.module
      .rule("vue")
      .use("vue-loader")
      .loader("vue-loader")
      .tap((options) => {
        options.compilerOptions.preserveWhitespace = true;
        return options;
      })
      .end();

    config.resolve.alias
      .set("components", resolve("src/components"))
      .set("mixin", resolve("src/mixin"))
      .set("api", resolve("src/api"))
      .set("@", resolve("src"))
      // .set('vue$', resolve('vue/dist/vue.esm.js'))
      .set("service", resolve("src/service"))
      .set("config", resolve("src/config"))
      .set("pages", resolve("src/pages"))
      .set("utils", resolve("src/utils"))
      .set("views", resolve("src/views"));
  },
  configureWebpack: (config) => {
    // 用cdn方式引入，则构建时要忽略相关资源
    if (isProduction || devNeedCdn) config.externals = cdn.externals;

    // 生产环境相关配置
    if (isProduction) {

      config.output.filename = `static/js/[name].${time_version}.js`
      config.output.chunkFilename = `static/js/[name].${time_version}.js`
      // 代码压缩
      config.plugins.push(
        new UglifyJsPlugin({
          uglifyOptions: {
            //生产环境自动删除console
            compress: {
              drop_debugger: true,
              drop_console: true,
              pure_funcs: ["console.log"],
            },
          },
          sourceMap: false,
          parallel: true,
        })
      );

      // gzip压缩
      const productionGzipExtensions = ["html", "js", "css"];
      config.plugins.push(
        new CompressionWebpackPlugin({
          filename: "[path].gz[query]",
          algorithm: "gzip",
          test: new RegExp("\\.(" + productionGzipExtensions.join("|") + ")$"),
          threshold: 10240, // 只有大小大于该值的资源会被处理 10240
          minRatio: 0.8, // 只有压缩率小于这个值的资源才会被处理
          deleteOriginalAssets: false, // 删除原文件
        })
      );

      // 公共代码抽离
      config.optimization = {
        splitChunks: {
          cacheGroups: {
            vendor: {
              chunks: "all",
              test: /node_modules/,
              name: "vendor",
              minChunks: 1,
              maxInitialRequests: 5,
              minSize: 0,
              priority: 100,
            },
            common: {
              chunks: "all",
              test: /[\\/]src[\\/]js[\\/]/,
              name: "common",
              minChunks: 2,
              maxInitialRequests: 5,
              minSize: 0,
              priority: 60,
            },
            styles: {
              name: "styles",
              test: /\.(sa|sc|c)ss$/,
              chunks: "all",
              enforce: true,
            },
            runtimeChunk: {
              name: "manifest",
            },
          },
        },
      };
    }
  },
  // 生产环境是否生成 sourceMap 文件
  productionSourceMap: false,
  //
  assetsDir: "static",
  // css相关配置
  css: {
    // 是否使用css分离插件 ExtractTextPlugin
    extract: true,
    // 开启 CSS source maps?
    sourceMap: true,
    // css预设器配置项
    loaderOptions: {},
    // 启用 CSS modules for all css / pre-processor files.
    requireModuleExtension: true,
  },
  // 在生产环境下为 Babel 和 TypeScript 使用 `thread-loader`
  // 在多核机器下会默认开启。
  parallel: require("os").cpus().length > 1,
  // PWA 插件相关配置
  // see https://github.com/vuejs/vue-cli/tree/dev/packages/%40vue/cli-plugin-pwa
  pwa: {},
  // webpack-dev-server 相关配置
  devServer: {
    open: process.platform === "darwin",
    host: "0.0.0.0",
    port: 80,
    https: false,
    hotOnly: false,
    // 设置代理
    proxy: null,
    disableHostCheck: true,
    allowedHosts: [".wd.legendshop.cn"],
    before: (app) => { },
  },
  // 第三方插件配置
  pluginOptions: {
    "style-resources-loader": {
      preProcessor: "stylus",
      patterns: [],
    },
  },
};
